﻿using Assets.Scripts.Bvh.Common;
using System.Collections.Generic;

namespace Assets.Scripts.Bvh.Cpu
{
    class AABBBuilder
    {
        public static void BuildAABB(RadixTreeNode[] interiorNodes, List<RadixTreeNode> leafNodes)
        {
            var visitCounts = new int[interiorNodes.Length];

            //遍历叶子结点
            foreach (var leaf in leafNodes)
            {
                var parentIndex = leaf.parentIndex;
                var min = leaf.aabb.minCorner;
                var max = leaf.aabb.maxCorner;

                //如果其父节点不是空
                while (parentIndex != -1)
                {
                    ref var interiorNode = ref interiorNodes[parentIndex];
                    var interAabb = interiorNode.aabb;
                    interiorNode.aabb = interAabb.Union(min, max);

                    //查看当前父节点被访问的次数
                    var visitCount = visitCounts[parentIndex];
                    //如果是第一次访问，则这个子节点的递归直接退出
                    if (visitCount == 0)
                    {
                        visitCounts[parentIndex]++;
                        break;
                    }

                    //我们只允许第二个子节点访问父节点时，继续向上查找。
                    min = interiorNode.aabb.minCorner;
                    max = interiorNode.aabb.maxCorner;
                    parentIndex = interiorNode.parentIndex;
                }
            }
        }
    }
}
